﻿using System;
using System.IO;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.LIB;
using SystemDiagramNew.SystemDiagramLegend;
using SystemDiagramNew.SystemDiagramLegend.DataDefine;
using SystemDiagramNew.Utils;

namespace SystemDiagramNew
{
	internal class LegendManager
	{
		public LegendManager(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
		}

		public void MappingWidthFamily2ndLegend()
		{
			new LegendMappingForm(this.m_Revit).ShowDialog();
		}

		public void LegendManage()
		{
			LegendEditor legendEditor = new LegendEditor(this.m_Revit);
			LegendManageForm legendManageForm = new LegendManageForm(this.m_Revit);
			while (legendManageForm.ShowDialog() == DialogResult.OK)
			{
				if (legendManageForm.theResultType == LegendManageForm.ResultType.RT_OnSelect)
				{
					LegendGroup currentSelectedLegendGroup = legendManageForm.CurrentSelectedLegendGroup;
					Legend currentSelectedLegend = legendManageForm.CurrentSelectedLegend;
					if (legendEditor.SelectLegendGraphInfos(ref currentSelectedLegend))
					{
						string text = Product.WorkingLocation + "exportSystemDiagramLegendInfo.xml";
						string text2 = AssistFunc.GetAppRootPath() + "\\Data\\exportSystemDiagramLegendInfo.xml";
						bool flag = false;
						if (!File.Exists(text))
						{
							flag = true;
						}
						if (File.GetLastWriteTime(text) < File.GetLastWriteTime(text2))
						{
							flag = true;
						}
						if (flag)
						{
							this.CopyFile(text2, text);
						}
						XMLKit.AddLegendInfoToLegendFile(text, currentSelectedLegendGroup);
					}
				}
				else if (legendManageForm.theResultType == LegendManageForm.ResultType.RT_OnDrawing)
				{
					LegendGroup currentSelectedLegendGroup2 = legendManageForm.CurrentSelectedLegendGroup;
					Legend currentSelectedLegend2 = legendManageForm.CurrentSelectedLegend;
					XYZ ptInsert = null;
					if (this.GetReferencePoint(ref ptInsert))
					{
						new DrawingKit(this.m_Revit, 0.0, legendManageForm.DrawLegendScale)
						{
							View = this.m_Revit.Application.ActiveUIDocument.ActiveView
						}.DrawingLegend(currentSelectedLegend2, ptInsert);
						this.m_Revit.UpdateModel(false);
					}
				}
			}
		}

		private void CopyFile(string sourceFileName, string destFileName)
		{
			try
			{
				File.Copy(sourceFileName, destFileName, true);
			}
			catch (Exception)
			{
			}
		}

		private bool GetReferencePoint(ref XYZ refPoint)
		{
			Selection selection = this.m_Revit.Application.ActiveUIDocument.Selection;
			try
			{
				refPoint = selection.PickPoint("选择插入点");
			}
			catch (Exception ex)
			{
				string message = ex.Message;
				return false;
			}
			return true;
		}

		private readonly ExternalCommandData m_Revit;
	}
}
